const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')

module.exports = {
	//输入输出
	entry: './src/index.js',
	output: {
		filename: 'script/[name].[contenthash].js',
		path: path.resolve(__dirname, './dist'),
		clean: true,
		assetModuleFilename: 'static/[contenthash][ext]',
	},

	//资源模块
	module: {
		rules: [
			/**
			 * 图片资源
			 * asset/resource 资源路径
			 * asset/inline base64格式
			 */

			//自动选择方式
			{
				test: /\.(jpg|png|gif|svg)$/i,
				type: 'asset',
				generator: {
					filename: 'images/[contenthash][ext]',
				},
				parser: {
					//自动选择临界值
					dataUrlCondition: {
						maxSize: 4 * 1024,
					},
				},
			},

			//文本资源 源代码方式
			{
				test: /\.txt$/,
				type: 'asset/source',
			},

			//css and less文件加载
			{
				test: /\.(css|less)$/,
				use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'],
			},

			//js打包
			{
				test: /\.js$/,
				exclude: /node_modules/,
				loader: 'babel-loader',
				options: {
					presets: ['@babel/preset-env'],
					plugins: [['@babel/plugin-transform-runtime']],
				},
			},
		],
	},

	optimization: {
		minimizer: [new CssMinimizerPlugin()],
	},

	//环境 development production
	mode: 'development',

	//调试代码
	devtool: 'inline-source-map',

	//插件
	plugins: [
		new HtmlWebpackPlugin({
			template: './index.html',
			filename: 'index.html',
			inject: 'body',
		}),

		new MiniCssExtractPlugin({
			filename: 'style/[contenthash].css',
		}),
	],

	//开发服务器
	devServer: {
		static: './dist',
	},
}
